#include"header/token.h"
#include"header/scanner.h"
#include"header/parser.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void check_token_info(){
    token tk = token_scan();
        while(tk->type != TOKEN_EOF){
            log_token(tk);
            puts("");
            tk = token_scan();
        }
        log_token(tk);
        puts("");
}

void check_syntax_error(int type){
    abt_declist declist = NULL;
    advance();
    declist = parse_program();
    if(type){
        if(type == 1){
            log_abt(declist);
        }
    }else{
        puts("\033[1msyntax check succeed, no error detected.\033[0m");
    }
}

void display_msg(){
    puts("\n\033[1mMini-C\033[0m running under OS X\n");
    puts("Copyright (C) Created by s0duku on 2020/9/2");
    puts("This is free software; see the source for copying conditions.");
    puts("https://gitee.com/s0duku/mini-c");
    puts("Gitee upload on Wednesday September 2, 2020 at 11:50 PM\n");
    puts("\033[31mUsage\033[0m: ./mini-c [\033[1mINPUT_FILE\033[0m] [\033[1mOPTION\033[0m]");
    puts("\n\033[1mOPTION:\033[0m\n");
    puts("-t\t check token infomation.");
    puts("-s\t check syntax error.");
    puts("-a\t display abstract syntax tree.");

    puts("");
}

int main(int n,char ** args){
    init_parser();
    if(n >= 2){
        FILE * fp = freopen(args[1],"r",stdin);
        if(!fp){
            puts("\033[31mfatal error\033[0m: can't open target file");
            return 0;
        }
        if(n == 3){
            if(!strcmp("-t",args[2])){
                check_token_info();
            }else if(!strcmp("-s",args[2])){
                check_syntax_error(0);
            }else if(!strcmp("-a",args[2])){
                check_syntax_error(1);
            }
            else{
                display_msg();
            }
        }else{
            display_msg();
        }
        return 0;
    }
    display_msg();
    return 0;
}